#include	"ShellList.h"
#include	"Shell.h"
#include	"ITank.h"
#include	<Configuration/Config.h>
#include	<Sound/SoundSystem.h>

ShellList::ShellList(Config * config, SoundSystem * soundSystem)
	:	m_shell()
	,	m_config(config)
	,	m_soundSystem(soundSystem)
	,	m_shot(0)
	,	m_explosion(0)
{
	m_shot = m_soundSystem->CreateSound("artwork\\Sounds\\Shot.wav");
	m_explosion = m_soundSystem->CreateSound("artwork\\Sounds\\Explosion.wav");
}

ShellList::~ShellList()
{
	clear();
}

void ShellList::update(double delay)
{
	std::list< Shell * >::iterator it = m_shell.begin();
	while(it != m_shell.end())
	{
		(*it)->update(delay);
		if(!((*it)->isActive()))
		{
			if((m_soundSystem != 0) && (m_explosion != 0))
			{
				m_soundSystem->PlaySound(m_explosion, m_config->sound.effectVolume);
			}
			it = m_shell.erase(it);
		}
		else
		{
			++it;
		}
	}
}

void ShellList::render() const
{
	for(std::list< Shell * >::const_iterator it = m_shell.begin();
		it != m_shell.end(); ++it)
	{
		(*it)->render();
	}
}

void ShellList::add(Shell * shell)
{
	if((m_soundSystem != 0) && (m_explosion != 0))
	{
		m_soundSystem->PlaySound(m_shot, m_config->sound.effectVolume);
	}
	m_shell.push_back(shell);
}

void ShellList::checkTank(ITank * tank)
{
	std::list< Shell * >::iterator it = m_shell.begin();
	while(it != m_shell.end())
	{
		if((*it)->isActive() &&
			(tank->isColliding((*it)->getPos())) &&
			(tank->isPlayer() != (*it)->isPlayers())
			)
		{
			if((m_soundSystem != 0) && (m_explosion != 0))
			{
				m_soundSystem->PlaySound(m_explosion, m_config->sound.effectVolume);
			}
			it = m_shell.erase(it);
			tank->destroy();
		}
		else
		{
			++it;
		}
	}
}

void ShellList::clear()
{
	for(std::list< Shell * >::iterator it = m_shell.begin();
		it != m_shell.end(); ++it)
	{
		delete (*it);
	}
	m_shell.clear();
}

